<script setup>
import { onMounted, ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElCarousel, ElCarouselItem, ElCard, ElButton, ElTag, ElLoading } from 'element-plus'
import request from '@/utils/request'
import { useRouteObserver } from '@/composables/useRouteObserver'
import { useRouteStore } from '@/stores/route'
import { useAuth } from '@/utils/useAuth'
import { IteratorFactory } from '@/utils/data-iterators'

const route = useRoute()
const router = useRouter()
const routeStore = useRouteStore()

// 设置路由观察者
const { setupDefaultObservers, addNavigationObserver } = useRouteObserver()

// 添加首页专用的导航观察者
const homeObserver = addNavigationObserver('HomePage', (routeInfo) => {
  if (routeInfo.path === '/home') {
    console.log('首页路由观察者：用户访问首页', routeInfo)
    // 可以在这里添加首页特定的逻辑，如数据预加载、统计等
    routeStore.setCachedData('homeVisitTime', Date.now())
  }
})

// 使用全局认证状态
const { userInfo, fetchUserInfo } = useAuth()

// 响应式数据
const banners = ref([
  {
    id: 1,
    title: '专业医疗，健康守护',
    subtitle: '权威专家在线问诊，24小时健康服务',
    image: 'https://via.placeholder.com/1200x300/4CAF50/ffffff?text=专业医疗',
    link: '#'
  },
  {
    id: 2,
    title: '快速预约，便捷就医',
    subtitle: '在线预约挂号，减少排队等待时间',
    image: 'https://via.placeholder.com/1200x300/2196F3/ffffff?text=快速预约',
    link: '#'
  },
  {
    id: 3,
    title: '健康管理，预防为主',
    subtitle: '个性化健康方案，科学管理您的健康',
    image: 'https://via.placeholder.com/1200x300/FF9800/ffffff?text=健康管理',
    link: '#'
  }
])

const departments = ref([])
const doctors = ref([])
const currentDepartment = ref(null)
const loading = ref(false)

// 预约相关数据
const appointmentDialog = ref(false)
const selectedDoctor = ref(null)
const appointmentForm = reactive({
  appointment_date: '',
  appointment_type: 'online',
  symptoms: ''
})
const appointmentLoading = ref(false)

const healthServices = ref([
  {
    id: 1,
    name: '在线问诊',
    icon: '💻',
    description: '专业医生在线咨询，24小时服务',
    features: ['视频问诊', '图文咨询', '电话咨询'],
    route: '/consultation'
  },
  {
    id: 2,
    name: '预约挂号',
    icon: '📅',
    description: '在线预约，减少排队等待',
    features: ['专家号预约', '普通号预约', '检查预约'],
    route: '/appointment'
  },
  {
    id: 3,
    name: '健康档案',
    icon: '📋',
    description: '个人健康信息管理',
    features: ['病历管理', '检查报告', '用药记录'],
    route: '/health-record'
  },
  {
    id: 4,
    name: '健康体检',
    icon: '🏥',
    description: '专业体检套餐推荐',
    features: ['体检预约', '报告解读', '健康建议'],
    route: '/health-checkup'
  }
])

// 地图/医院数据
const mapContainer = ref(null)
const mapLoaded = ref(false)
const hospitals = ref([])
let amapInstance = null
let markers = []
let infoWindows = new Map()
const currentCenter = ref([116.397428, 39.90923])
const locating = ref(false)
let myMarker = null
let myCircle = null
const searchKeyword = ref('医院')

async function loadAmapJs() {
  return new Promise((resolve, reject) => {
    if (window.AMap) return resolve()
    const script = document.createElement('script')
    script.src = 'https://webapi.amap.com/maps?v=2.0&key=5696bda08f34d11fcb4b179d5879cf4a'
    script.async = true
    script.onload = () => resolve()
    script.onerror = reject
    document.head.appendChild(script)
  })
}

async function initMap() {
  try {
    await loadAmapJs()
    // @ts-ignore
    amapInstance = new window.AMap.Map(mapContainer.value, {
      viewMode: '3D',
      zoom: 11,
      center: currentCenter.value,
    })
    mapLoaded.value = true
  } catch (e) {
    console.error('加载高德JS失败', e)
  }
}

function getBrowserLocation() {
  return new Promise((resolve, reject) => {
    if (!('geolocation' in navigator)) return reject(new Error('浏览器不支持定位'))
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const { latitude, longitude } = pos.coords
        resolve([longitude, latitude])
      },
      (err) => reject(err),
      { enableHighAccuracy: true, timeout: 7000, maximumAge: 0 }
    )
  })
}

async function locateAndRefresh() {
  try {
    locating.value = true
    const lnglat = await getBrowserLocation()
    if (Array.isArray(lnglat)) {
      currentCenter.value = lnglat
      if (amapInstance) {
        // @ts-ignore
        amapInstance.setCenter(lnglat)
        // @ts-ignore
        amapInstance.setZoom(12)
      }
      // 显示我的位置标记与圈
      try {
        // @ts-ignore
        myMarker && amapInstance.remove(myMarker)
        // @ts-ignore
        myCircle && amapInstance.remove(myCircle)
        // @ts-ignore
        myMarker = new window.AMap.Marker({ position: lnglat, title: '我的位置', icon: 'https://webapi.amap.com/theme/v1.3/markers/n/loc.png' })
        // @ts-ignore
        myCircle = new window.AMap.Circle({ center: lnglat, radius: 300, fillColor: '#409EFF55', strokeColor: '#409EFF' })
        // @ts-ignore
        amapInstance.add([myMarker, myCircle])
      } catch {}
      await fetchHospitals('')
    }
  } catch (e) {
    console.warn('定位失败，使用默认城市', e)
    // 定位失败时仍然加载一次（默认北京）
    await fetchHospitals('北京')
  } finally {
    locating.value = false
  }
}

async function fetchHospitals(city = '', keywords = '医院') {
  const params = { city, keywords }
  if (currentCenter.value) {
    params.location = currentCenter.value.join(',')
  }
  const { data } = await request.get('/api/map/hospitals', { params })
  if (data && data.code === 0) {
    hospitals.value = data.data || []
    renderMarkers()
  }
}

function clearMarkers() {
  if (!amapInstance || !markers.length) return
  // @ts-ignore
  amapInstance.remove(markers)
  markers = []
}

function renderMarkers() {
  if (!amapInstance) return
  clearMarkers()
  hospitals.value.forEach((h) => {
    if (!h.location) return
    const [lng, lat] = h.location.split(',').map(Number)
    // @ts-ignore
    const marker = new window.AMap.Marker({ position: [lng, lat], title: h.name })
    // @ts-ignore
    const info = new window.AMap.InfoWindow({
      content: `<div style="min-width:220px">
        <div style="font-weight:600;margin-bottom:4px">${h.name}</div>
        <div>评分：${h.rating || '暂无'}${h.distance ? (' · 距离：' + (Number(h.distance)/1000).toFixed(1) + 'km') : ''}</div>
        <div>开放时间：${h.open_time || '未知'}</div>
        <div>地址：${h.address || ''}</div>
        <div>电话：${h.tel || ''}</div>
      </div>`
    })
    marker.on('click', () => {
      info.open(amapInstance, marker.getPosition())
    })
    markers.push(marker)
    infoWindows.set(h.name, { marker, info, lnglat: [lng, lat] })
  })
  // @ts-ignore
  amapInstance.add(markers)
}

function focusHospital(h) {
  const entry = infoWindows.get(h.name)
  if (!entry) return
  const { marker, info, lnglat } = entry
  // @ts-ignore
  amapInstance.setCenter(lnglat)
  // @ts-ignore
  amapInstance.setZoom(14)
  info.open(amapInstance, marker.getPosition())
}

// 顶部次级导航
const navItems = [
  { key: 'home', label: '首页', route: '/home' },
  { key: 'experts', label: '找专家', route: '/appointment' },
  { key: 'hospitals', label: '找医院', route: '#map' },
  { key: 'knowledge', label: '查知识', route: '/knowledge' },
  { key: 'qa', label: '健康问答', route: '/about' },
  { key: 'articles', label: '科普文章', route: '/about' },
  { key: 'consult', label: '患友问诊', route: '/about' },
]
const activeNav = ref('home')

function handleNavClick(item) {
  activeNav.value = item.key
  if (typeof item.route === 'string') {
    if (item.route === '#map') {
      // 滚动到地图区域
      const el = document.querySelector('.map-section')
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' })
    } else {
      router.push(item.route)
    }
  }
}

// 获取科室列表
async function fetchDepartments() {
  try {
    const { data } = await request.get('/api/departments/')
    if (data && data.code === 0) {
      departments.value = data.data.map(dept => ({
        ...dept,
        icon: dept.icon || getDepartmentIcon(dept.name)
      }))
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    ElMessage.error('获取科室列表失败')
  }
}

// 根据科室名称获取图标
function getDepartmentIcon(name) {
  const iconMap = {
    '内科': '🫀',
    '外科': '🔪',
    '妇产科': '👩',
    '儿科': '👶',
    '眼科': '👁️',
    '口腔科': '🦷',
    '皮肤科': '👩‍⚕️',
    '中医科': '🌿',
    '急诊科': '🚨',
    '康复科': '🏃'
  }
  return iconMap[name] || '🏥'
}

// 获取科室医生列表
async function fetchDoctorsByDepartment(departmentId) {
  loading.value = true
  try {
    const { data } = await request.get(`/api/departments/${departmentId}/doctors/`)
    if (data && data.code === 0) {
      doctors.value = data.data.doctors
      currentDepartment.value = data.data.department
      ElMessage.success(`已加载 ${data.data.total} 位医生`)
    } else {
      ElMessage.error(data?.msg || '获取医生列表失败')
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  // 初始化路由观察者
  setupDefaultObservers()

  // 检查URL中是否有token（从第三方登录回调）
  const token = route.query.token
  console.log('[Home] 检查URL token:', token)
  if (token) {
    try {
      console.log('[Home] 发现token，开始处理...')
      
      // 验证token格式（简单检查）
      if (typeof token !== 'string' || token.length < 10) {
        throw new Error('无效的token格式')
      }
      
      // 保存token
      localStorage.setItem('token', token)
      console.log('[Home] token已保存到localStorage')
      
      // 立即更新路由store
      routeStore.setAuthenticated(true)
      routeStore.setUserInfo({ token })
      
      // 清除URL中的token参数
      window.history.replaceState({}, document.title, window.location.pathname)
      
      ElMessage({
        message: '第三方登录成功！欢迎回来',
        type: 'success',
        duration: 3000,
        showClose: true
      })
      
      console.log('[Home] 第三方登录处理完成')
      
    } catch (error) {
      console.error('[Home] token处理失败:', error)
      ElMessage({
        message: `登录处理失败: ${error.message}`,
        type: 'error',
        duration: 5000,
        showClose: true
      })
      
      // 清除可能的无效token
      localStorage.removeItem('token')
      sessionStorage.removeItem('token')
      
      // 重定向到登录页面
      setTimeout(() => {
        router.replace('/')
      }, 2000)
      return
    }
  }

  // 获取用户信息（会自动更新userInfo）
  await fetchUserInfo()

  // 获取科室列表
  fetchDepartments()

  // 地图与医院列表：优先定位
  initMap().then(() => locateAndRefresh())
})

function onSearch() {
  fetchHospitals('', (searchKeyword.value || '医院').trim())
}

function handleDepartmentClick(department) {
  ElMessage.info(`正在加载 ${department.name} 的医生信息...`)
  fetchDoctorsByDepartment(department.id)
}

function handleDoctorClick(doctor) {
  // 检查用户是否已登录
  if (!userInfo.isLoggedIn) {
    ElMessage.warning('请先登录后再预约医生')
    router.push('/')
    return
  }

  // 使用迭代器展示医生信息
  showDoctorAppointmentDialog(doctor)
}

function showDoctorAppointmentDialog(doctor) {
  selectedDoctor.value = doctor
  appointmentForm.appointment_date = ''
  appointmentForm.appointment_type = 'online'
  appointmentForm.symptoms = ''
  appointmentDialog.value = true

  ElMessage.info(`正在为您展示 ${doctor.name} 医生的预约信息`)
}

function handleServiceClick(service) {
  if (service.route) {
    router.push(service.route)
  } else {
    ElMessage.info(`点击了服务：${service.name}`)
  }
}

function handleLogin() {
  // 跳转到登录页面
  window.location.href = '/'
}

function handleConsultation(doctor) {
  handleDoctorClick(doctor)
}

// 使用迭代器添加预约
async function submitAppointment() {
  if (!selectedDoctor.value) {
    ElMessage.error('请选择医生')
    return
  }

  // 表单验证
  if (!appointmentForm.appointment_date) {
    ElMessage.error('请选择预约时间')
    return
  }

  appointmentLoading.value = true

  try {
    // 首先测试认证状态
    console.log('测试认证状态...')
    try {
      const authTest = await request.get('/api/test-auth/')
      console.log('认证测试结果:', authTest.data)

      if (authTest.data.code !== 0) {
        ElMessage.error('认证失败，请重新登录')
        router.push('/')
        return
      }
    } catch (authError) {
      console.error('认证测试失败:', authError)
      ElMessage.error('认证状态异常，请重新登录')
      router.push('/')
      return
    }

    const appointmentData = {
      doctor_id: selectedDoctor.value.id,
      appointment_date: appointmentForm.appointment_date,
      appointment_type: appointmentForm.appointment_type,
      symptoms: appointmentForm.symptoms
    }

    console.log('提交预约数据:', appointmentData)

    const { data } = await request.post('/api/appointments/add/', appointmentData)

    console.log('预约响应:', data)

    if (data.code === 0) {
      ElMessage.success('预约添加成功！正在跳转到我的预约...')
      appointmentDialog.value = false

      // 使用迭代器显示统计信息
      const stats = data.data.statistics
      ElMessage.info(`您现在有 ${stats.total_appointments} 个预约，其中 ${stats.pending_appointments} 个待处理`)

      // 跳转到我的预约页面
      setTimeout(() => {
        router.push('/my-appointments')
      }, 2000) // 稍微延长时间，让用户看到统计信息
    } else {
      ElMessage.error(data.msg || '预约失败')

      // 如果是认证错误，跳转到登录页
      if (data.code === 401) {
        setTimeout(() => {
          router.push('/')
        }, 1000)
      }
    }
  } catch (error) {
    console.error('预约错误:', error)

    // 检查是否是认证错误
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      setTimeout(() => {
        router.push('/')
      }, 1000)
    } else {
      ElMessage.error(`预约失败：${error.response?.data?.msg || error.message || '请稍后重试'}`)
    }
  } finally {
    appointmentLoading.value = false
  }
}

// 使用迭代器过滤和统计医生
function analyzeCurrentDoctors() {
  if (doctors.value.length === 0) {
    ElMessage.warning('当前没有医生数据可分析')
    return
  }

  // 创建医生迭代器进行分析
  const doctorIterator = IteratorFactory.createDoctorIterator(doctors.value, {})

  let totalDoctors = 0
  let highRatedDoctors = 0
  let totalFee = 0
  const specialtiesSet = new Set()

  for (const doctor of doctorIterator) {
    totalDoctors++
    if (doctor.rating >= 4.0) {
      highRatedDoctors++
    }
    totalFee += doctor.fee || 0
    doctor.specialties?.forEach(specialty => specialtiesSet.add(specialty))
  }

  const avgFee = totalDoctors > 0 ? (totalFee / totalDoctors).toFixed(2) : 0

  ElMessage.success(`当前科室分析：共 ${totalDoctors} 位医生，${highRatedDoctors} 位高评分医生（≥4.0分），平均费用 ¥${avgFee}`)
  console.log('医生分析结果:', {
    totalDoctors,
    highRatedDoctors,
    avgFee,
    specialtiesCount: specialtiesSet.size,
    specialties: Array.from(specialtiesSet)
  })
}

// 测试预约功能（无需认证）
async function testAppointment() {
  if (!selectedDoctor.value) {
    ElMessage.error('请选择医生')
    return
  }

  appointmentLoading.value = true

  try {
    const appointmentData = {
      doctor_id: selectedDoctor.value.id,
      appointment_date: appointmentForm.appointment_date || new Date().toISOString().slice(0, 19).replace('T', ' '),
      appointment_type: appointmentForm.appointment_type,
      symptoms: appointmentForm.symptoms
    }

    console.log('测试预约数据:', appointmentData)

    const { data } = await request.post('/api/appointments/simple/', appointmentData)

    console.log('测试预约响应:', data)

    if (data.code === 0) {
      ElMessage.success('测试预约创建成功！正在跳转到我的预约...')
      appointmentDialog.value = false

      ElMessage.info(`预约号：${data.data.appointment.appointment_no}`)

      // 跳转到我的预约页面
      setTimeout(() => {
        router.push('/my-appointments')
      }, 2000)
    } else {
      ElMessage.error(data.msg || '测试预约失败')
    }
  } catch (error) {
    console.error('测试预约错误:', error)
    ElMessage.error(`测试预约失败：${error.response?.data?.msg || error.message || '请稍后重试'}`)
  } finally {
    appointmentLoading.value = false
  }
}
</script>

<template>
  <div class="medical-home">

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 轮播图 -->
      <section class="banner-section">
        <el-carousel height="300px" indicator-position="outside">
          <el-carousel-item v-for="banner in banners" :key="banner.id">
            <div class="banner-item" :style="{ backgroundImage: `url(${banner.image})` }">
              <div class="banner-content">
                <h2>{{ banner.title }}</h2>
                <p>{{ banner.subtitle }}</p>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </section>

      <!-- 科室分类 -->
      <section class="departments-section">
        <div class="section-title">
          <h3>科室导航</h3>
        </div>
        <div class="departments-grid">
          <div
            v-for="department in departments"
            :key="department.id"
            class="department-item"
            @click="handleDepartmentClick(department)"
          >
            <div class="department-icon">{{ department.icon }}</div>
            <div class="department-info">
              <span class="department-name">{{ department.name }}</span>
              <span class="department-desc">{{ department.description }}</span>
            </div>
          </div>
        </div>
      </section>

      <!-- 医生列表区域 -->
      <section v-if="currentDepartment" class="doctors-section">
        <div class="section-title">
          <div class="title-content">
            <h3>{{ currentDepartment.name }} - 医生列表</h3>
            <p class="section-subtitle">{{ currentDepartment.description }}</p>
          </div>
          <div class="title-actions">
            <el-button
              type="info"
              size="small"
              @click="analyzeCurrentDoctors"
              :disabled="doctors.length === 0"
            >
              🔄 迭代器分析
            </el-button>
          </div>
        </div>
        
        <div v-loading="loading" class="doctors-grid">
          <el-card
            v-for="doctor in doctors"
            :key="doctor.id"
            class="doctor-card"
            @click="handleDoctorClick(doctor)"
          >
            <div class="doctor-avatar">
              <img :src="doctor.avatar" :alt="doctor.name" />
            </div>
            <div class="doctor-info">
              <h4 class="doctor-name">{{ doctor.name }}</h4>
              <p class="doctor-title">{{ doctor.title }} · {{ doctor.department }}</p>
              <div class="doctor-stats">
                <el-tag size="small" type="success">经验 {{ doctor.experience_years }}年</el-tag>
                <el-tag size="small" type="warning">评分 {{ doctor.rating }}</el-tag>
                <el-tag v-if="doctor.is_featured" size="small" type="danger">推荐</el-tag>
              </div>
              <div class="doctor-specialties">
                <span v-for="specialty in doctor.specialties" :key="specialty" class="specialty-tag">
                  {{ specialty }}
                </span>
              </div>
              <div v-if="doctor.introduction" class="doctor-intro">
                <p>{{ doctor.introduction }}</p>
              </div>
              <div class="doctor-actions">
                <el-button type="primary" size="small" @click.stop="handleConsultation(doctor)">
                  咨询 ¥{{ doctor.consultation_fee }}
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        
        <div v-if="!loading && doctors.length === 0" class="no-doctors">
          <p>该科室暂无医生信息</p>
        </div>
      </section>

      <!-- 健康服务 -->
      <section class="services-section">
        <div class="section-title">
          <h3>健康服务</h3>
        </div>
        <div class="services-grid">
          <div
            v-for="service in healthServices"
            :key="service.id"
            class="service-item"
            @click="handleServiceClick(service)"
          >
            <div class="service-icon">{{ service.icon }}</div>
            <h4>{{ service.name }}</h4>
            <p>{{ service.description }}</p>
            <div class="service-features">
              <span v-for="feature in service.features" :key="feature" class="feature-tag">
                {{ feature }}
              </span>
            </div>
          </div>
        </div>
      </section>

      <!-- 医院地图 -->
      <section class="map-section">
        <div class="section-title section-title--map">
          <h3>附近医院地图</h3>
          <div class="map-actions">
            <el-input v-model="searchKeyword" placeholder="输入关键词（如：医院/儿科/中医院）" size="small" clearable @keyup.enter.native="onSearch" style="width: 280px;" />
            <el-button size="small" type="primary" @click="onSearch">搜索</el-button>
            <el-button size="small" :loading="locating" @click="locateAndRefresh">定位到我</el-button>
          </div>
        </div>
        <div class="map-layout">
          <div class="map" ref="mapContainer"></div>
          <div class="hospital-list">
            <div class="hospital-item" v-for="h in hospitals" :key="h.name" @click="focusHospital(h)">
              <div class="name">{{ h.name }}</div>
              <div class="meta">
                评分：{{ h.rating || '暂无' }}
                <template v-if="h.distance"> · 距离：{{ (Number(h.distance)/1000).toFixed(1) }}km</template>
                · 开放：{{ h.open_time || '未知' }}
              </div>
              <div class="addr">{{ h.address }}</div>
            </div>
          </div>
        </div>
      </section>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <div class="footer-content">
        <div class="footer-links">
          <a href="#">关于我们</a>
          <a href="#">联系我们</a>
          <a href="#">联系客服</a>
          <a href="#">医生入驻</a>
          <a href="#">医院合作</a>
        </div>
        <div class="footer-copyright">
          <p>Copyright © 2024 京东医疗 版权所有</p>
          <p>互联网医疗信息服务许可证 | 医疗器械经营许可证</p>
        </div>
      </div>
    </footer>

    <!-- 预约对话框 -->
    <el-dialog
      v-model="appointmentDialog"
      title="医生预约"
      width="500px"
      :before-close="() => appointmentDialog = false"
    >
      <div v-if="selectedDoctor" class="appointment-dialog">
        <!-- 医生信息展示 -->
        <div class="doctor-info-card">
          <div class="doctor-avatar">
            <img :src="selectedDoctor.avatar" :alt="selectedDoctor.name" />
          </div>
          <div class="doctor-details">
            <h3>{{ selectedDoctor.name }}</h3>
            <p>{{ selectedDoctor.title }} · {{ selectedDoctor.department }}</p>
            <div class="doctor-stats">
              <el-tag size="small" type="success">经验 {{ selectedDoctor.experience_years }}年</el-tag>
              <el-tag size="small" type="warning">评分 {{ selectedDoctor.rating }}</el-tag>
              <el-tag v-if="selectedDoctor.is_featured" size="small" type="danger">推荐</el-tag>
            </div>
            <div class="consultation-fee">
              <span class="fee-label">咨询费：</span>
              <span class="fee-amount">¥{{ selectedDoctor.consultation_fee }}</span>
            </div>
          </div>
        </div>

        <!-- 预约表单 -->
        <el-form :model="appointmentForm" label-width="100px" style="margin-top: 20px;">
          <el-form-item label="预约类型">
            <el-select v-model="appointmentForm.appointment_type" style="width: 100%;">
              <el-option label="在线咨询" value="online" />
              <el-option label="视频问诊" value="video" />
              <el-option label="电话咨询" value="phone" />
              <el-option label="线下就诊" value="offline" />
            </el-select>
          </el-form-item>

          <el-form-item label="预约时间">
            <el-date-picker
              v-model="appointmentForm.appointment_date"
              type="datetime"
              placeholder="选择预约时间"
              style="width: 100%;"
              :disabled-date="(date) => date < new Date()"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="症状描述">
            <el-input
              v-model="appointmentForm.symptoms"
              type="textarea"
              :rows="3"
              placeholder="请简要描述您的症状或需要咨询的问题"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>

        <!-- 迭代器功能说明 -->
        <div class="iterator-note">
          <p><strong>🔄 迭代器功能：</strong></p>
          <ul>
            <li>自动检查是否已有该医生的待处理预约</li>
            <li>预约成功后实时统计您的预约数量</li>
            <li>使用迭代器模式优化数据处理性能</li>
          </ul>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appointmentDialog = false">取消</el-button>
          <el-button
            type="warning"
            @click="testAppointment"
            :loading="appointmentLoading"
          >
            测试预约（无需认证）
          </el-button>
          <el-button
            type="primary"
            @click="submitAppointment"
            :loading="appointmentLoading"
          >
            {{ appointmentLoading ? '提交中...' : '确认预约' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.medical-home {
  min-height: 100vh;
  background-color: #f8f9fa;
}

/* 顶部导航栏 */
.header {
  background-color: #4CAF50;
  color: white;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.nav-tabs {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 56px;
}

.nav-tab {
  position: relative;
  font-size: 16px;
  color: #ffffff;
  cursor: pointer;
  padding: 4px 8px 10px;
}

.nav-tab .underline {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0;
  width: 28px;
  height: 3px;
  background: transparent;
  border-radius: 3px;
}

.nav-tab.active {
  color: #00e0ee;
}

.nav-tab.active .underline {
  background: #00e0ee;
}

.logo h1 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}

.search-bar {
  flex: 1;
  max-width: 500px;
  margin: 0 40px;
}

.search-input {
  width: 100%;
}

.user-actions {
  display: flex;
  gap: 20px;
}

.user-info, .login-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 主要内容区域 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 轮播图 */
.banner-section {
  margin-bottom: 40px;
}

.banner-item {
  height: 300px;
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.banner-content {
  text-align: center;
  color: white;
  background: rgba(0,0,0,0.5);
  padding: 30px;
  border-radius: 8px;
}

.banner-content h2 {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: bold;
}

.banner-content p {
  margin: 0;
  font-size: 16px;
}

/* 科室区域 */
.departments-section {
  margin-bottom: 40px;
}

.section-title {
  margin-bottom: 20px;
}
.section-title--map { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.map-actions { display: flex; align-items: center; gap: 8px; }

.section-title h3 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.section-subtitle {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.departments-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.department-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.department-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.department-icon {
  font-size: 32px;
}

.department-info {
  display: flex;
  flex-direction: column;
}

.department-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.department-desc {
  font-size: 12px;
  color: #666;
}

/* 医生区域 */
.doctors-section {
  margin-bottom: 40px;
}

.doctors-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.doctor-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.doctor-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.doctor-avatar {
  text-align: center;
  margin-bottom: 15px;
}

.doctor-avatar img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.doctor-info {
  text-align: center;
}

.doctor-name {
  margin: 0 0 5px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.doctor-title {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #666;
}

.doctor-stats {
  margin-bottom: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}

.doctor-specialties {
  margin-bottom: 15px;
}

.specialty-tag {
  display: inline-block;
  background: #e3f2fd;
  color: #1976d2;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin: 2px;
}

.doctor-intro {
  margin-bottom: 15px;
}

.doctor-intro p {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  margin: 0;
}

.doctor-actions {
  margin-top: 15px;
}

.no-doctors {
  text-align: center;
  padding: 40px;
  color: #999;
}

/* 服务区域 */
.services-section {
  margin-bottom: 40px;
}

.services-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.service-item {
  background: white;
  padding: 30px 20px;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.service-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.service-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.service-item h4 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #333;
}

.service-item p {
  margin: 0 0 15px 0;
  color: #666;
  font-size: 14px;
}

.service-features {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 5px;
}

.feature-tag {
  background: #f0f0f0;
  color: #666;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 页脚 */
.footer {
  background-color: #333;
  color: white;
  padding: 40px 20px 20px;
  margin-top: 60px;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
}

.footer-links {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.footer-links a {
  color: white;
  text-decoration: none;
  font-size: 14px;
}

.footer-links a:hover {
  text-decoration: underline;
}

.footer-copyright {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #555;
}

.footer-copyright p {
  margin: 5px 0;
  color: #999;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 10px 0;
  }

  .search-bar {
    margin: 10px 0;
    max-width: 100%;
  }

  .departments-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .doctors-grid {
    grid-template-columns: 1fr;
  }

  .services-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 标题区域样式 */
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-content {
  flex: 1;
}

.title-actions {
  display: flex;
  gap: 10px;
}

/* 预约对话框样式 */
.appointment-dialog {
  padding: 10px 0;
}

.doctor-info-card {
  display: flex;
  gap: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.doctor-info-card .doctor-avatar {
  flex-shrink: 0;
}

.doctor-info-card .doctor-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.doctor-details {
  flex: 1;
}

.doctor-details h3 {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 18px;
}

.doctor-details p {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.doctor-details .doctor-stats {
  display: flex;
  gap: 8px;
  margin-bottom: 10px;
}

.consultation-fee {
  display: flex;
  align-items: center;
  gap: 5px;
}

.fee-label {
  color: #909399;
  font-size: 14px;
}

.fee-amount {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.iterator-note {
  background: #e8f4fd;
  border: 1px solid #c6e2ff;
  border-radius: 6px;
  padding: 12px;
  margin-top: 15px;
}

.iterator-note p {
  margin: 0 0 8px 0;
  color: #409eff;
  font-size: 14px;
}

.iterator-note ul {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  font-size: 13px;
}

.iterator-note li {
  margin-bottom: 3px;
}

/* 地图区域 */
.map-section { margin-top: 20px; }
.map-layout { display: grid; grid-template-columns: 2fr 1fr; gap: 16px; }
.map { height: 420px; background: #f0f2f5; border-radius: 8px; }
.hospital-list { max-height: 420px; overflow: auto; background: #fff; border-radius: 8px; padding: 10px; box-shadow: 0 2px 4px rgba(0,0,0,0.06); }
.hospital-item { padding: 10px; border-bottom: 1px solid #f2f2f2; }
.hospital-item:last-child { border-bottom: none; }
.hospital-item .name { font-weight: 600; color: #333; }
.hospital-item .meta { color: #666; font-size: 12px; margin-top: 4px; }
.hospital-item .addr { color: #909399; font-size: 12px; margin-top: 2px; }
</style>